#!/usr/bin/python

import sys
import os
import os.path
import codecs
import json
import jrdUtils
from pyXls import *

#----------------------------------------------------
# Global Variables
#----------------------------------------------------

_xlsPath = 'ffos_wimdata_ng/wlanguage/src/'
_xlsFile = _xlsPath + 'strings.xls'
# All languages comparison table, to translate the language name of XLS  into shortname.
_allLangsDict = {}

_langList = jrdUtils.getLangsListFromJson()

#store column informations
_langInXlsList = []
#store id informations
_idDict = {}
# Language starting position of excel file
_langStartPosition = 7

# create workbook
_wb = Workbook()
_ws0 = _wb.add_sheet(u'MESSAGE')
_ws1 = _wb.add_sheet('Zone')
_ws2 = _wb.add_sheet('Deleted')

#----------------------------------------------------
# Functions
#----------------------------------------------------

def initIdDictAndLangList(tableDict):
    langs = jrdUtils.getLangsShortnameDictFromlangsList(_langList)
    #initialize idDict and langList
    for cell in tableDict:
        #generate message id list
        if cell[1] == 0 and cell[0]!=0 :
            strId = tableDict[cell]
            _idDict[cell[0]-1] = strId

        #generate language list
        if cell[0] == 0 and cell[1] >= _langStartPosition:
            key = _allLangsDict[tableDict[cell]]
            if langs.has_key(key):
                _langInXlsList.append((tableDict[cell], cell[1]))
    #print _langInXlsList

def xlsToMsgDict(tableDict):
    msgDict = {}

    for idx in _idDict:
        msgId = _idDict[idx]
        msgDict[msgId] = {}
        rowDict = msgDict[msgId]
        for lang in _langInXlsList:
            sLangName = _allLangsDict[lang[0]]
            row = idx+1
            column = lang[1]
            if tableDict.has_key(((row,column))):
                rowDict[sLangName] = tableDict[(row,column)]
        #print rowDict
    #print msgDict
    return msgDict

def msgDictToFileDict(msgDict):
    fileDict = {}

    for items in msgDict:
        i = items.rfind(':')
        msgId = items[i+1:]
        filePathStr = items[:i]
        translation = msgDict[items]

        #print filePathStr,msgId,translation

        msgTuple = (msgId, translation)

        if not fileDict.has_key(filePathStr):
            fileDict[filePathStr] = []
        fileDict[filePathStr].append(msgTuple)

    #print fileDict
    return fileDict

def fileDictToOutPutDict(fileDict):
    outPutDict = {}
    for files in fileDict:
        pathAndName = files.replace(':','/') + '.properties'
        #print pathAndName

        msgList = fileDict[files]
        for msg in msgList:
            msgid = msg[0]
            strDict = msg[1]
            for lang in strDict:
                filepath = _l10nPath + lang + '/apps/' + pathAndName
                if not outPutDict.has_key(filepath):
                    outPutDict[filepath] = ''
                msgstr =  msgid + '=' + strDict[lang] + '\n'
                outPutDict[filepath] += msgstr

    return outPutDict

def searchProofread(tdict):
    ldict = {}
    for cell in tdict:
        if cell[1] == 9 and cell[0]!=0 :
            key = tdict[(cell[0],0)]
            value = tdict[cell]
            ldict[key] = value

    print '    Modified proofreading: %s' % len(ldict)
    return ldict

def parseFile2Json(fileName):
    path = _xlsPath + fileName + '.xls'

    if os.path.isfile(path):
        sheets = parse_xls(path)
        tableDict = sheets[0][1]
        langDict = searchProofread(tableDict)

        outputJson = _xlsPath + '.json/' + fileName + '.json'
        if not os.path.exists(_xlsPath + '.json/'):
            os.makedirs(_xlsPath + '.json/')

        if os.path.isfile(outputJson):
            os.remove(outputJson)
        os.mknod(outputJson)

        fOut = open(outputJson,'wb')
        fOut.write((json.dumps(langDict,ensure_ascii=False, sort_keys=True, indent=2)).encode('utf-8'))
        fOut.close()

        return langDict

    else:
        assert False, 'Not find Proofreading file!'

def genJrdDict(path):
    #print path
    sheets = parse_xls(path)
    tableDict = sheets[0][1]
    initIdDictAndLangList(tableDict)

    msgDict = xlsToMsgDict(tableDict)

    return msgDict

def mergeJrdAndProofread(ldict, jrdDict, lang):

    for key in ldict:
        if not jrdDict.has_key(key):
            jrdDict[key] = {}
        jrdDict[key][lang] = ldict[key]

    return jrdDict

def genJrdl10nJson(jrdDict):
    jrdJson = _xlsPath + '.json/jrd_l10n.json'
    if os.path.isfile(jrdJson):
        os.remove(jrdJson)
    os.mknod(jrdJson)

    fOut = open(jrdJson,'wb')
    fOut.write((json.dumps(jrdDict,ensure_ascii=False, sort_keys=True, indent=2)).encode('utf-8'))
    fOut.close()

def setStyles():
    fnt = Font()
    fnt.name = 'Times New Roman'
    al = Alignment()
    al.horz = Alignment.HORZ_LEFT
    al.vert = Alignment.VERT_CENTER
    style = XFStyle()
    style.font = fnt
    style.alignment = al
    return style

def writeAttrTitlesToSheet(style):
    _ws0.write(0, 0, u'RefName',style)
    _ws0.write(0, 1, u'ModOP',style)
    _ws0.write(0, 2, u'Info',style)
    _ws0.write(0, 3, u'ZoneType',style)
    _ws0.write(0, 4, u'IsMono',style)
    _ws0.write(0, 5, u'IsUK',style)
    _ws0.write(0, 6, u'IsGSM',style)
    _ws0.write(0, 7, u'IsTradUpdatable',style)

    _ws1.write(0, 0, u'zonetype', style)
    _ws1.write(0, 1, u'width', style)
    _ws1.write(0, 2, u'height', style)
    _ws1.write(0, 3, u'text_size', style)
    _ws1.write(0, 4, u'FontFamily', style)
    _ws1.write(0, 5, u'Italic', style)
    _ws1.write(0, 6, u'Bold', style)
    _ws1.write(0, 7, u'ZoneDesc', style)

    _ws2.write(0, 0, u'Name', style)
    _ws2.write(0, 1, u'LogDate', style)
    _ws2.write(0, 2, u'RefName', style)
    _ws2.write(0, 3, u'LogAction', style)

def writeMsgToSheet1(msgDict,style):
    #sort MSGDICT
    sortDict = sorted(msgDict.items(), key=lambda e:e[0], reverse=False)

    for item in sortDict:
        t_row = sortDict.index(item)+1
        #write ID to excel
        _ws0.write( t_row , 0, item[0], style)
        for lang in _langList:
            t_column = _langList.index(lang) + _langStartPosition
            _ws0.write(0, t_column, lang[1], style)
            if item[1].get(lang[0]):
                #write Translation to excel
                _ws0.write(t_row,t_column,(item[1])[lang[0]], style)
    _wb.save(_xlsFile)

def genJrdl10nXls(jrdDict):
    # set styles
    s = setStyles()
    # write head line to xls
    writeAttrTitlesToSheet(s)
    # write messsges to excel
    writeMsgToSheet1(jrdDict,s)
    print 'Merge proofreading successed!'
def genAllLangsDictFromlangList():
    for lang in _langList:
        _allLangsDict[lang[1]] = lang[0]

#----------------------------------------------------
# main
#----------------------------------------------------

def main():
    #Generate global dict _allLangsDict form _langList.
    genAllLangsDictFromlangList()
    #print _allLangsDict
    #Generate jrdDict from strings.xls
    jrdDict = genJrdDict(_xlsFile)

    #The arguments should be named as fullname in _langList. e.g.: Polish.
    if(len(sys.argv)>1):
        fileList = sys.argv
        #Handle every language, parse the xls file into json
        for i in range(1,len(sys.argv)):
            #Parse each proofreading xls into json files
            langName = fileList[i]
            print 'Start to merge proofreading of %s...' % langName
            ldict = parseFile2Json(langName)
            #Merge jrdDict and each proofread dict.
            jrdDict = mergeJrdAndProofread(ldict,jrdDict, _allLangsDict[langName])

    print 'Total number of Jrd strings is: %s' % len(jrdDict)
    #Output jrd translation dict as jrd_l10n.json
    genJrdl10nJson(jrdDict)
    #Output Merged translation dict as strings.xls
    genJrdl10nXls(jrdDict)

if __name__ == '__main__':
    main()
